package com.ynny.librarysystemmanager.service.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.ynny.librarysystemmanager.common.ServerReturnCode;
import com.ynny.librarysystemmanager.entity.*;
import com.ynny.librarysystemmanager.entity.Record;
import com.ynny.librarysystemmanager.mapper.BookMapper;
import com.ynny.librarysystemmanager.mapper.RecordMapper;
import com.ynny.librarysystemmanager.mapper.UserMapper;
import com.ynny.librarysystemmanager.service.RecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

@Service
public class RecordServiceImpl implements RecordService {

    @Autowired
    UserMapper userMapper;
    @Autowired
    BookMapper bookMapper;
    @Autowired
    RecordMapper recordMapper;

    private static final String BORROW_BOOK = "borrow";
    private static final String RETURN_BOOK = "return";


    @Transactional
    @Override
    public int borrowerBook(Integer userId, Integer bookId) {
        /*
            借书逻辑
            1.校验用户
              1.1  用户是否存在
              1.2  用户是否可用
              1.3  用户的权限  -----学生 老师 管理员  游客

           2.校验图书
             2.1 图书是否存在
             2.2 图书是否可用
             2.3 库存是否充足

          3. 借阅记录是否存在 ------- 不允许重复借同一本书

          4.操作
            4.1 添加一个借阅信息  借阅人 书名  借阅时间  逾期时间  借阅状态
            4.2 图书的库存 -1
         */
        User user = userMapper.selectOne(userId);

        if (user == null){
            return UserErrorReturnCode.USER_NOT_FOUND;
        }

        if (user.getIsDelete().equals(1)){
            return UserErrorReturnCode.USER_IS_DELETE;
        }

        // 1 学生 2 老师 3 管理员  4游客
        if (user.getRole().getRoleId() == RoleIdentity.ROLE_USER.getRoleId() ){
            return UserErrorReturnCode.USER_IS_NOT_ALLOW;
        }

        Book book = bookMapper.getBookById(bookId);

        if (book == null){
            return BookErrorReturnCode.BOOK_NOT_FOUND;
        }

        if (book.getIsDelete().equals(1)){
            return BookErrorReturnCode.BOOK_IS_DELETE;
        }

        if (book.getStorage() <= 0){
            return BookErrorReturnCode.BOOK_IS_NOT_STORAGE;
        }

        Record record = recordMapper.selectRecordByBorrowerIdAndBookId(userId , bookId);

        if (record != null){

            return RecordErrorReturnCode.RECORD_REPEAT;
        }

        //借阅操作
        Record newRecord = new Record();
        newRecord.setBookId(bookId);
        newRecord.setBookName(book.getBookName());
        newRecord.setBorrowerId(userId);
        newRecord.setBorrowerName(user.getName());
        newRecord.setBorrowerTime(LocalDateTime.now());

        LocalDateTime offset = LocalDateTimeUtil
                .offset(LocalDateTime.now(),
                        1, ChronoUnit.MONTHS);
        newRecord.setEndTime(offset);

        int i = recordMapper.insert(newRecord);

        if ( i > 0){
            int res = bookMapper.updateBookStorage(bookId, BORROW_BOOK);
            return res > 0 ? ServerReturnCode.SUCCESS : ServerReturnCode.ERROR;
        }else {
            return ServerReturnCode.ERROR;
        }

    }

    @Override
    public int returnBook(Integer userId, Integer bookId) {

        /**
         * 还书逻辑
         *
         * 校验
         * 1.用户是否存在
         * 2.用户是否可用
         * 3.是否逾期   ----》
         *
         *
         * 1.图书是否存在
         * 2.借阅与 归还 图书是否一致
         *
         * 操作
         * 修改借阅记录  归还时间  借阅状态 已归还
         * 图书库存 + 1
         *
         */
        User user = userMapper.selectOne(userId);
        if (user == null){
            return UserErrorReturnCode.USER_NOT_FOUND;
        }
        if (user.getIsDelete().equals(1)){
            return UserErrorReturnCode.USER_IS_DELETE;
        }

        Record record = recordMapper
                .selectRecordByBorrowerIdAndBookId(userId, bookId);
        if (record == null){
            return RecordErrorReturnCode.RECORD_IS_NULL;
        }
        //逾期判断
        if (record.getStatus().equals(BookStatus.Overdue.getCode())){
            userMapper.delete(userId , 1);
        }else {
            record.setStatus(BookStatus.RETURNED.getCode());
        }

        //归还图书
        // 1 2 3
        record.setReturnTime(LocalDateTime.now());
        int i = recordMapper.update(record);
        if ( i > 0){
            //库存+1
            int j = bookMapper.updateBookStorage(bookId, RETURN_BOOK);
            return j > 0 ? ServerReturnCode.SUCCESS : ServerReturnCode.ERROR;

        }else {
            return ServerReturnCode.ERROR;
        }

    }


}
